import base64
import re

import requests

# 1、 主页面
login_url = "https://kyfw.12306.cn/otn/resources/login.html"
headers = {
    "Referer": "https://www.12306.cn/index/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"
}
# response = requests.get(url=login_url, headers=headers)
# print(response.cookies)
session = requests.Session()
# 添加
session.headers.update(headers)

response = session.get(url=login_url)
# print(response.cookies)
# cookies = response.cookies
# 2、下载验证码
capt_url = "https://kyfw.12306.cn/passport/captcha/captcha-image64?login_site=E&module=login&rand=sjrand&1580737745071&callback=jQuery19103163659468210125_1580737674102&_=1580737674103"
capt_response = session.get(capt_url)
# cookies = capt_response.cookies
# print(capt_response.text)
# 获取图片的信息
img_data = re.findall(b'"image":"(.*?)"', capt_response.content)[0]
# print(img_data)  # 有base64编码
img_data = base64.b64decode(img_data)  # base64解码
# print(img_data)
with open('capt_img.jpg', 'wb') as f:
    f.write(img_data)
# 验证验证码
check_url = "https://kyfw.12306.cn/passport/captcha/captcha-check"


def get_index(indexs):
    """选择图片坐标"""
    map = {
        '1': '40,43',
        '2': '18,43',
        '3': '180,43',
        '4': '258,43',
        '5': '37,117',
        '6': '103,117',
        '7': '178,117',
        '8': '250,117'
    }
    indexs = indexs.split(',')
    res = []
    for i in indexs:
        res.append(map[i])
    return ','.join(res)


data = {
    "callback": "jQuery19103163659468210125_1580737674102",
    "answer": get_index(input('请输入正确的图片（逗号分隔）：')),
    "rand": "sjrand",
    "login_site": "E",
    "_": "1580737674105"
}
check_res = session.get(
    check_url,
    params=data)
print(check_res.text)
